package com.leetcode.stackandqueue.demo5;

import java.util.Arrays;
import java.util.Stack;

/**
 * @Author Zan
 * @Create 2024/7/12 22:45
 * @ClassName: Test
 * @Description : https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/  逆波兰表达式求值
 */
public class Test {
    public static void main(String[] args) {
        String[] str = new String[]{"4","13","5","/","+"};
        Solution solution = new Solution();
        int i = solution.evalRPN(str);
        System.out.println(i);
    }
}

class Solution {
    public int evalRPN(String[] tokens) {
        // 将tokens里面的字符串一个一个取出来，放入栈中，如果碰到运算符，进行运算
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            if (!token.equals("+") && !token.equals("-") && !token.equals("*") && !token.equals("/")) {
                stack.push(Integer.parseInt(token));
            } else {
                // 碰到运算符 - 进行运算
                Integer pop1 = stack.pop();
                Integer pop2 = stack.pop();
                switch (token) {
                    case "+":
                        stack.push(pop1 + pop2);
                        break;
                    case "-":
                        stack.push((-1) * pop1 + pop2);
                        break;
                    case "*":
                        stack.push(pop1 * pop2);
                        break;
                    case "/":
                        stack.push(pop2 / pop1);
                        break;
                }
            }
        }
        return stack.pop();
    }
}